/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bayu.controller;

import com.bayu.services.dao.RejectCastingDao;
import com.bayu.services.entity.RejectCasting;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author Bayu
 */
@Controller
@RequestMapping("/casting-update.htm")
public class CastingUpdate {
    RejectCastingDao rejectCastingDao;
    @Autowired
    private void setRejectCastingDao(RejectCastingDao rejectCastingDao){
      this.rejectCastingDao = rejectCastingDao;
    }

    @RequestMapping(method = RequestMethod.GET)
    public void displayForm(ModelMap map,String id){
        List list = this.rejectCastingDao.getById(Long.parseLong(id));
        map.addAttribute("data", list);
    }

    @RequestMapping(method = RequestMethod.POST)
    public String proccessForm(@ModelAttribute("rejectCasting") RejectCasting rejectCasting , BindingResult result,ModelMap map, String date,HttpServletRequest req){
            DateFormat formarter = new SimpleDateFormat("yy-MM-dd");
            Date tgl = null;

            //exchangeCurrency.setDate(tgl);
            if(result.hasFieldErrors("date")){
                try {
                    tgl = formarter.parse(date);
                    rejectCasting.setDate(tgl);
                } catch (ParseException ex) {
                    Logger.getLogger(CastingUpdate.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            /*
            List total = this.rejectCastingDao.custom("select count(*) from RejectCasting where date='"+tgl+"'");

            String strTotal=total.get(0).toString();
            int c = Integer.valueOf(strTotal).intValue();

            if(c > 0){
                return "redirect:ErrorDuplicate.html";
            }else{
             */

             String id = req.getParameter("id");

                if(id!=null){
                     rejectCasting.setId(Long.parseLong(id));
                     this.rejectCastingDao.update(rejectCasting);
                     return "redirect:view-casting-data.htm?msg=Data has been updated";
                }else{
                    return "redirect:casting-update.htm";
                }
            //}



            //map.addAttribute("hasil", "Data Sudah Disimpan");

    }
}
